package com.miao.api;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.miao.base.exception.XueChengPlusException;
import com.miao.config.AlipayConfig;
import com.miao.dto.AddOrderDto;
import com.miao.dto.PayRecordDto;
import com.miao.po.XcPayRecord;
import com.miao.service.OrderService;
import com.miao.service.PayRecordService;
import com.miao.util.SecurityUtil;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//订单相关接口
@Slf4j
@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private PayRecordService payRecordService;

    @Value("${pay.alipay.APP_ID}")
    String APP_ID;
    @Value("${pay.alipay.APP_PRIVATE_KEY}")
    String APP_PRIVATE_KEY;
    @Value("${pay.alipay.ALIPAY_PUBLIC_KEY}")
    String ALIPAY_PUBLIC_KEY;



    //生成二维码
    @ResponseBody
    @PostMapping("/generatepaycode")
    public PayRecordDto generateCode(@RequestBody AddOrderDto addOrderDto){
        String Uid = SecurityUtil.getUser().getId();
        //插入订单信息，插入支付信息，生成二维码
        return orderService.creatCode(Uid, addOrderDto);
    }

    //支付接口
    @GetMapping("/requestpay")
    public void requestpay(String payNo, HttpServletResponse httpResponse) throws IOException {
        //如果payNo不存在则提示重新发起支付
        XcPayRecord payRecord = payRecordService.getPayRecordByPayno(payNo);
        if(payRecord == null){
            XueChengPlusException.cast("请重新点击支付获取二维码");
        }
        //支付状态
        String status = payRecord.getStatus();
        if("601002".equals(status)){
            XueChengPlusException.cast("订单已支付，请勿重复支付。");
        }


        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, APP_ID, APP_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);//获得初始化的AlipayClient
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        //request.setNotifyUrl("");
        //同步跳转地址，仅支持http/https
        //request.setReturnUrl("");
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", payRecord.getPayNo());
        //支付金额，最小值0.01元
        bizContent.put("total_amount", payRecord.getTotalPrice());
        //订单标题，不可使用特殊符号
        bizContent.put("subject", "售卖课程");

        /******可选参数******/
        //手机网站支付默认传值QUICK_WAP_WAY
        bizContent.put("product_code", "QUICK_WAP_WAY");
        //bizContent.put("time_expire", "2022-08-01 22:00:00");


        request.setBizContent(bizContent.toString());
        AlipayTradeWapPayResponse response = null;
        try {
            response = alipayClient.pageExecute(request,"POST");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        // 如果需要返回GET请求，请使用
//         AlipayTradeWapPayResponse response = alipayClient.pageExecute(request,"GET");
        String pageRedirectionData = response.getBody();
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpResponse.getWriter().write(pageRedirectionData);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();

        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }

    //查询支付结果
    @GetMapping("/payresult")
    @ResponseBody
    public PayRecordDto getResultOfPay(String payNo){
        //查询支付结果
        //若支付成功，更新订单表和支付表的状态
        return orderService.queryResult(payNo);


    }

}
